<template>
<div class="todo-container">
    <div class="todo-wrap">
      <h3>记事本</h3>
      <Header :addTodo="addTodo"/>
      <List :todos="todos" :deleteTodo="deleteTodo" :updateTodo="updateTodo" />
      <Footer :todos="todos" :checkAll="checkAll" :clearAllCompletedTodos="clearAllCompletedTodos" />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from 'vue'
import Header from './components/Header.vue'
import List from './components/List.vue'
import Footer from './components/Footer.vue'
import {Todo} from './types/todo'
import {saveTodos,readTodos} from './utils/localStorageUtils'


export default defineComponent({
  name: 'App',
  components: {
    Header,
    List,
    Footer
  },
  setup() {
    // const state = reactive<{todos:Todo[]}>({
    //   todos: [
    //     { id: 1, title: '奔驰', isCompleted: false },
    //     { id: 2, title: '宝马', isCompleted: true },
    //     { id: 3, title: '奥迪', isCompleted: false }
    //   ]
    // })
    
    const state = reactive<{todos:Todo[]}>({
      todos: []
    })
    //界面加载完毕后过了一会再读取数据
    onMounted(() => {
      // setTimeout(()=>{
      //   state.todos = readTodos()
      // },1000)
      //不用定时器直接页面一加载出来就读取本地存储的数据也可以
      state.todos = readTodos()
    })
    //监视操作，如果todos数据变化，直接存储在浏览器的缓存中
    // watch(()=>state.todos,(value)=>{
    //   localStorageUtils.setItem('todos_key',JSON.stringify(value))
    // }),{deep:true}

    // watch(()=>state.todos,(value)=>{
    //    //保存到浏览器缓存中
    //   saveTodos(value)
    // }),{deep:true}
    watch(() => state.todos, saveTodos, { deep: true })

    

    //添加数据的方法,给子组件传过去，在Header组件中用
    const addTodo= (todo:Todo)=>{
        state.todos.unshift(todo)
    }
    //删除数据的方法  数据在哪方法就写在哪，在Item组件中用
    const deleteTodo =(index:number)=>{
        state.todos.splice(index,1)
    }
    //修改todo的isCompleted属性,在item组件中用
    const updateTodo = (todo:Todo,isCompleted:boolean)=>{
      todo.isCompleted = isCompleted
      console.log(todo)
    }
    //全选或全不选的方法
    const checkAll =(isCompleted:Boolean)=>{
      state.todos.forEach(todo=>{
        todo.isCompleted =isCompleted
      })
    }
    //清除所有选中的数据
    const clearAllCompletedTodos =()=>{
      state.todos=state.todos.filter(todo=>!todo.isCompleted)
    }
    

    return{
      //使得html中不用写state.todos  将todos传出去
      ...toRefs(state),
      addTodo,
      deleteTodo,
      updateTodo,
      checkAll,
      clearAllCompletedTodos
    }
  }
})
</script>


<style scoped>
/*app*/
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
h3{
 color: rgb(20, 207, 45)
}
</style>
